// pages/order/order.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    address: '',
    isCheck: true,
    orderInfo: '',
    coupon: ''
  },

  getCoupon() {
    wx.$https('orders.coupon.list', {
      couponInfo: `${this.data.goodsDetail.shopId||0}|${this.data.skuDetail.price*this.data.skuDetail.amount}`
    }).then(res => {
      res = wx.$coupon(res)
      res.sort((a, b) => {
        return b.price - a.price
      })
      res.map(v => {
        return v.isUse = false
      })
      this.setData({
        coupon: res
      })
      if (res.length != 0) {
        this.DefaultCoupon()
      } else {
        this.calcSum()
      }
    })
  },

  DefaultCoupon() {
    let coupon = this.data.coupon
    if (coupon) {
      let detail = this.data.goodsDetail
      detail.coupon = coupon[0]
      coupon[0].isUse = true
      this.setData({
        goodsDetail: detail,
        coupon: coupon
      })
    }
    this.calcSum()
  },

  chooseCoupon(e) {
    wx.$nav('/pages/coupon/coupon', {
      list: JSON.stringify(this.data.coupon),
      shopId: this.data.goodsDetail.shopId || 0,
      currentCouponId: this.data.goodsDetail.coupon ? this.data.goodsDetail.coupon.accountCouponId : -1,
      sum: this.data.goodsDetail.money
    })
  },

  setCoupon(coupon, shopId, currentCouponId) {
    let detail = this.data.goodsDetail
    let cList = this.data.coupon
    detail.coupon = coupon
    for (let x in cList) {
      if (currentCouponId == cList[x].accountCouponId) {
        cList[x].isUse = false
      }
      if (coupon.accountCouponId == cList[x].accountCouponId) {
        cList[x].isUse = true
      }
    }
    this.setData({
      goodsDetail: detail,
      coupon: cList
    })
    this.calcSum()
  },

  calcSum() {
    let goodsDetail = this.data.goodsDetail
    let coupon = goodsDetail.coupon
    let skuDetail = this.data.skuDetail
    goodsDetail.money = (skuDetail.price * skuDetail.amount).toFixed(2)
    if (!coupon) {
      goodsDetail.sum = (skuDetail.price * skuDetail.amount+parseFloat(goodsDetail.postPrice)).toFixed(2);
    } else {
      goodsDetail.sum = (skuDetail.price * skuDetail.amount + parseFloat(goodsDetail.postPrice) - coupon.price).toFixed(2)
    }
    this.setData({
      goodsDetail: goodsDetail
    })
  },

  defaultAddress() {
    wx.$https('address.default.selected').then(res => {
      this.setData({
        address: res || ''
      })
    })
  },

  ordersAdd() {
    let goodsInfo = ''
    let skuDetail = this.data.skuDetail
    let goodsDetail = this.data.goodsDetail
    goodsInfo = `${skuDetail.goodsSkuId}|${skuDetail.amount}${goodsDetail.coupon?'|'+goodsDetail.coupon.accountCouponId:''}`
    var me = this;
    wx.$https('orders.add', {
      addressId: this.data.address.addressId,
      goodsInfo: goodsInfo
    }).then(res => {
      wx.$unifiedorder(res.ordersIds, function () {
        wx.redirectTo({
          url: '/pages/orderList/orderList?status=2&orderId=' + res.ordersIds
        });
      }, function () {
        wx.redirectTo({
          url: '/pages/orderList/orderList?status=0&orderId=' + res.ordersIds
        });
      })
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let that = this
    this.setData({
      skuDetail: JSON.parse(options.skuDetail)
      // goodsDetail: JSON.parse(options.goodsDetail)
    })
    wx.$getPrev(this, {
      goodsDetail: 'goodsDetail'
    })
    //注释部分为用微信默认地址系统
    // let address = wx.getStorageSync('address')
    // that.setData({
    //   address: address
    // })
    // wx.getSetting({
    //   success(res) {
    //     if (res.authSetting['scope.address'] == true) {
    //       that.setData({
    //         scopeAddress: true
    //       })
    //     }
    //   }
    // })
  },


  //onload之后的方法 为用微信默认地址系统的方法
  getAddress() {
    wx.$nav('/pages/addressList/addressList', {
      way: 'from_order'
    })
  },

  getSite() {
    let that = this
    wx.getSetting({
      success(res) {
        if (res.authSetting['scope.address'] == false) {
          wx.showModal({
            title: '获取地址',
            content: '未开启访问地址权限，是否前往开启？',
            success(res) {
              if (!res.cancel) {
                wx.openSetting({
                  success() {
                    that.choAddress()
                  }
                })
              }
            }
          })
        } else {
          that.choAddress()
        }
      }
    })
  },

  choAddress() {
    let that = this
    wx.chooseAddress({
      success: (res) => {
        that.setData({
          address: res
        })
        wx.setStorageSync('address', res)
      },
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if (this.data.isCheck) {
      this.defaultAddress()
    } else {
      this.setData({
        isCheck: true
      })
    }
    this.getCoupon()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },
  unifiedorder: function (orderId) {
    var that = this;
    wx.showLoading({
      title: '正在支付...'
    })
    wx.$https('app.payment', {
      orderId: orderId,
    }).then(ress => {
      wx.hideLoading();
      var order = ress;
      //吊起微信支付
      wx.requestPayment({
        timeStamp: order.timeStamp + "",
        nonceStr: order.nonceStr,
        package: order.package,
        signType: 'MD5',
        paySign: order.paySign,
        success: function (res) {
          wx.redirectTo({
            url: '/pages/orderList/orderList?status=1&orderId=' + that.data.orderId
          });
        },
        fail: function (res) {
          // 用户取消支付
          if ("requestPayment:fail cancel" == res.errMsg) {
            wx.redirectTo({
              url: '/pages/orderList/orderList?status=0&orderId=' + that.data.orderId
            });
          }
        }
      })
    })

  },
})